<?php
class BlogModel{
	
#TODO settings
	protected function zapiszUstawienia(){
		global $config;
		foreach ($config->ustawienia_blog as $id => $wartosc) {
			$id__ = tools::__adodb('getOne',"SELECT id  FROM ".BLSETTIN." WHERE id = ".tools::__mres($id),true,$this->db); 
			if($id == $id__){
				tools::__adodb("exec","UPDATE ".BLSETTIN." SET wartosc = ".tools::__mres($wartosc)." WHERE id = ".tools::__mres($id),true,$this->db);
			}else{
				tools::__adodb("exec","INSERT INTO ".BLSETTIN." (id, wartosc) VALUES (".tools::__mres($id).",".tools::__mres($wartosc).");",true,$this->db);
			}
		}
	}
		
	protected function pobierzUstawienia(){	
		$q__ = "SELECT id, wartosc FROM ".BLSETTIN;
		return tools::__adodb('getAssoc',$q__,true,$this->db);
	}
	
	protected function wyzerujUstawieniaPG(){
		return tools::__adodb('exec',"DELETE FROM ".BLSETTIN,true,$this->db);
	}
	
#TODO categorry
	protected function zapiszNowaKategorie(){
		global $config;
		$q__ = "INSERT INTO ".BLCATEGO." (blcID,blcPage,blcStatus,blcLp) 
			VALUES (NULL,".tools::__mres($config->page).",0,0)";
		tools::__adodb('exec',$q__,true,$this->db);
		
		$blcID = $this->db->lastInsertId();
		if(is_array($config->blcNazwa)){
			foreach ($config->blcNazwa as $lang => $blcNazwa) {
				$blcOPis__ = (isset($config->blcOpis[$lang])) ? $config->blcOpis[$lang] : '';
				$q__ = "INSERT INTO ".BLCATELA." (blcID,blcLang,blcNazwa,blcOpis) 
					VALUES (".tools::__mres($blcID).",'{$lang}',".tools::__mres($blcNazwa).",".tools::__mres($blcOPis__).")";
				tools::__adodb('exec',$q__,true,$this->db);				
			}
		}else{
			$q__ = "INSERT INTO ".BLCATELA." (blcID,blcLang,blcNazwa) 
				VALUES (".tools::__mres($blcID).",'{$config->__lang}',".tools::__mres($config->blcNazwa).")";
			tools::__adodb('exec',$q__,true,$this->db);
		}	
		return $blcID;
	}
	
	protected function zapiszEdytowanaKategorie(){
		global $config;
		
		if(is_array($config->blcNazwa)){
			foreach ($config->blcNazwa as $lang => $kateg) {
				$q__ = "SELECT COUNT(*) FROM ".BLCATEGO." a 
					LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
					WHERE b.blcLang = '{$lang}' AND a.blcID = '{$config->blcID}'";
				$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
				if($istnieje == 1){
					$q__ = "UPDATE ".BLCATELA." SET blcNazwa = ".tools::__mres($kateg)."
						WHERE blcID = ".tools::__mres($config->blcID)." AND blcLang = ".tools::__mres($lang);
					tools::__adodb('exec',$q__,true,$this->db);	
				}else{
					$q__ = "INSERT INTO ".BLCATELA." (blcID,blcLang,blcNazwa) 
					VALUES (".tools::__mres($config->blcID).",'{$lang}',".tools::__mres($kateg).")";
					tools::__adodb('exec',$q__,true,$this->db);		
				}
			}
			
		}else{
			$q__ = "UPDATE ".BLCATELA." SET blcNazwa = ".tools::__mres($config->blcNazwa)."
				WHERE blcID = ".tools::__mres($config->blcID)." AND blcLang = ".tools::__mres($config->blcLang);
			tools::__adodb('exec',$q__,true,$this->db);
		}	

		if(is_array($config->blcOpis)){
				foreach ($config->blcOpis as $lang => $Opis__) {
					$q__ = "SELECT COUNT(*) FROM ".BLCATEGO." a 
						LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
						WHERE b.blcLang = '{$lang}' AND a.blcID = '{$config->blcID}'";
					$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
					if($istnieje == 1){
						$q__ = "UPDATE ".BLCATELA." SET blcOpis = ".tools::__mres($Opis__)."
							WHERE blcID = ".tools::__mres($config->blcID)." AND blcLang = ".tools::__mres($lang);
						tools::__adodb('exec',$q__,true,$this->db);	
					}else{
						$q__ = "INSERT INTO ".BLCATELA." (blcID,blcLang,blcOpis) 
						VALUES (".tools::__mres($config->blcID).",'{$lang}',".tools::__mres($Opis__).")";
						tools::__adodb('exec',$q__,true,$this->db);		
					}
				}
			}
	}
	
	protected function pobiezKategorie($blcID = null,$lang=null, $pgStatus=''){
		global $objSession,$config;
		if(is_null($blcID) || empty($blcID)){
			// lista wszystkich kategorii dla domyslnego jezyka
			
			if ( $objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){			
				$q__ = "SELECT a.*, b.blcNazwa, b.blcLang, b.blcOpis FROM ".BLCATEGO." a 
					LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
					WHERE b.blcLang = '{$config->__lang}' 
					AND a.blcPage = ".tools::__mres($config->page)." ORDER BY a.blcLp";
			}else{
				$q__ = "SELECT a.*, b.blcNazwa, b.blcLang, b.blcOpis FROM ".BLCATEGO." a 
					LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
					WHERE b.blcLang = '{$config->__lang}' 
					AND a.blcPage = ".tools::__mres($config->page)."
					AND a.blcStatus = 0 	ORDER BY a.blcLp"; 		
	
			}
			return tools::__adodb('getAll',$q__,true,$this->db);
		}else{
			if  ($lang != null){
				// kategoria dla wybranego jezyka
				$q__ = "SELECT a.*, b.blcNazwa, b.blcOpis, b.blcLang FROM ".BLCATEGO." a 
					LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
					WHERE b.blcLang = '{$lang}' AND a.blcID = '$blcID'";
				return tools::__adodb('getRow',$q__,true,$this->db);
			}else{
				// kategoria wiele jezykow
				$q__ = "SELECT a.*, b.blcNazwa, b.blcOpis, b.blcLang FROM ".BLCATEGO." a 
					LEFT JOIN ".BLCATELA." b ON b.blcID = a.blcID 
					WHERE a.blcID = '$blcID'";
				return tools::__adodb('getAll',$q__,true,$this->db);							
			}
		}
	}
	
	protected function pgLpUp($id_kategoria=null){
		$q__ = "SELECT pgLp,pgID FROM ".BLCATEGO." WHERE pgID = {$id_kategoria}";
		$curent_row = tools::__adodb('getRow',$q__,true,$this->db);
		$curent_lp__ = $curent_row['pgLp'];		
		$new_lp__ =  $curent_lp__- 1;
		if ($curent_lp__ > 1){
			if(tools::__adodb('exec',"UPDATE ".BLCATEGO." SET pgLp={$curent_lp__} WHERE pgLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".BLCATEGO." SET pgLp={$new_lp__} WHERE pgID = {$id_kategoria}",true,$this->db);
		}		
	}
	
	protected function pgLpDown($id_kategoria=null){
		$curent_row = tools::__adodb('getRow',"SELECT pgLp  FROM ".BLCATEGO." WHERE pgID = {$id_kategoria}",true,$this->db);
		$curent_lp__ = $curent_row['pgLp'];
		$max_lp__ = tools::__adodb('getOne',"SELECT MAX(pgLp) FROM ".BLCATEGO ,true,$this->db);
		$new_lp__ = (is_numeric($curent_lp__) && $curent_lp__ == 0) ? $max_lp__ + 1  : $curent_lp__+ 1;
		if ($curent_lp__ < $max_lp__ || $max_lp__ == 0 || $curent_lp__ == 0){
			if(tools::__adodb('exec',"UPDATE ".BLCATEGO." SET pgLp={$curent_lp__} WHERE pgLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".BLCATEGO." SET pgLp={$new_lp__} WHERE pgID = {$id_kategoria}",true,$this->db);
		}		
	}

	protected function phLpUp($blwID_=null){
		$q__ = "SELECT blwLp,blcID FROM ".BLOWPISY." WHERE blwID = {$blwID_}";
		$curent_row = tools::__adodb('getRow',$q__,true,$this->db);
		$curent_lp__ = $curent_row['blwLp'];		
		$new_lp__ =  $curent_lp__- 1;
		if ($curent_lp__ > 1){
			if(tools::__adodb('exec',"UPDATE ".BLOWPISY." SET blwLp={$curent_lp__} WHERE blwLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".BLOWPISY." SET blwLp={$new_lp__} WHERE blwID = {$blwID_}",true,$this->db);
		}		
	}
	
	protected function phLpDown($blwID_=null){
		$curent_row = tools::__adodb('getRow',"SELECT blwLp,blcID  FROM ".BLOWPISY." WHERE blwID = {$blwID_}",true,$this->db);
		$curent_lp__ = $curent_row['blwLp'];
		$max_lp__ = tools::__adodb('getOne',"SELECT MAX(blwLp) FROM ".BLOWPISY ,true,$this->db);
		$new_lp__ = (is_numeric($curent_lp__) && $curent_lp__ == 0) ? $max_lp__ + 1  : $curent_lp__+ 1;
		if ($curent_lp__ < $max_lp__ || $max_lp__ == 0 || $curent_lp__ == 0){
			if(tools::__adodb('exec',"UPDATE ".BLOWPISY." SET blwLp={$curent_lp__} WHERE blwLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".BLOWPISY." SET blwLp={$new_lp__} WHERE blwID = {$blwID_}",true,$this->db);
		}		
	}
	protected function zliczAktywneKategorie(){
		$count_ =  tools::__adodb('getOne',"SELECT Count(*) FROM ".BLCATEGO." WHERE blcStatus = 0",true,$this->db);
		return $count_;
	}
	
	protected function domyslnaGaleria(){
		$count_ =  tools::__adodb('getOne',"SELECT Min(blcID) FROM ".BLCATEGO." WHERE blcStatus = 0",true,$this->db);
		return $count_;
	}
	
	protected function zliczWpisyKategorii($blcID){
		$count_ =  tools::__adodb('getOne',"SELECT Count(*) FROM ".BLOWPISY." WHERE blcID = '{$blcID}'",true,$this->db);
		return $count_;
	}


	protected function pobiezWpisyJednejKategorii($blcID = null,$lang=null, $phStatus='', $limit=''){
		if($blcID == 'najnowsze'){
			// najnowsze wpisy
			$q__ = "SELECT a.*, b.blwTemat, b.blwWpis, b.blwLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
				WHERE b.blwLang = '{$lang}' {$phStatus}  
				ORDER BY a.blwData DESC {$limit}";
			//echo $q__;
			return tools::__adodb('getAll',$q__,true,$this->db);			
			
		}
		if  ($lang != null){
			// galeria dla wybranego jezyka
			$q__ = "SELECT a.*, b.blwTemat, b.blwWpis, b.blwLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
				WHERE b.blwLang = '{$lang}' AND a.blcID = '{$blcID}' {$phStatus}  
				ORDER BY a.blwData DESC {$limit}";
			return tools::__adodb('getAll',$q__,true,$this->db);
		}else{
			// galeria wiele jezykow
			$q__ = "SELECT a.*, b.blwTemat, b.blwWpis, b.blwLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
				WHERE a.blcID = '$blcID' ORDER BY a.blwData DESC {$limit}";
			return tools::__adodb('getAll',$q__,true,$this->db);							
		}

	}

	protected function pobierzJedenWpis($blwID = null,$lang=null){
		if  ($lang != null){
			// zdjecie dla jednego jezyka
			$q__ = "SELECT a.*, b.blwTemat, b.blwWpis, b.blwLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
				WHERE b.blwLang = '{$lang}' AND a.blwID = '$blwID'";
			$result = tools::__adodb('getRow',$q__,true,$this->db);
			return (is_array($result)) ? $result : false;
		}else{
			// galeria wiele jezykow
			$q__ = "SELECT a.*, b.blwTemat, b.blwWpis, b.blwLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
				WHERE a.blwID = '$blwID'";
			$result = tools::__adodb('getAll',$q__,true,$this->db);
			return (is_array($result)) ? $result : false;							
		}

	}
	
	protected function pobiezIkonkeKategorii($blcID = null, $limit=null){
		global $config;
			$limit2 = $limit+1;
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang FROM ".BLOWPISY." a 
				LEFT JOIN ".BLOWPILA." b ON b.phID = a.phID 
				WHERE b.phLang = '{$config->__lang}' AND a.pgID = '$blcID' LIMIT $limit,$limit2";
			return tools::__adodb('getRow',$q__,true,$this->db);
	}
		
	protected function zapiszNowyWpisKategorii($blcID){
		global $config;
		$lp__ =  tools::__adodb('getOne',"SELECT Max(blwLp) FROM ".BLOWPISY." WHERE blcID = {$blcID}",true,$this->db);
		$q = "INSERT INTO ".BLOWPISY." (blwID,blcID,blwData,blwStatus,blwLp) 
			VALUES (NULL,{$blcID}, '".date('Y-m-d H:i:s')."',0,".tools::__mres($lp__).")";
		tools::__adodb('exec',$q,true,$this->db);
		$blwID = $this->db->lastInsertId();
		$this->zapiszDaneWpisuBloga($blwID);
			

		// zapis plikow
		foreach ($_FILES as $fieldName => $file) {	
		
			if ($file['size'] <= $this->maxfilesize && $file['error'] == 0 ) {
				$q = "INSERT INTO ".BLOZDJEC." (blpID,blwID,blpFile,blpStatus,blpLp) 
				VALUES (NULL,{$blwID}, '{$blwID}_".tools::__link($file['name'])."',0,".tools::__mres($lp__).")";
				tools::__adodb('exec',$q,true,$this->db);
				$up=move_uploaded_file($file['tmp_name'],  "{$this->BlogRootPath}{$blwID}_".tools::__link($file['name']) );
			}else{
				$up = false;
			}
			
			$lp__++;
		}

	}
	
	
	protected function podmienPlikGalerii(){
		global $config;
		// zapis pliku i danych
		
		foreach ($_FILES as $fieldName => $file) {
		
			if ($file['size'] <= $this->maxfilesize && $file['size'] > 0 && $file['error'] == 0 ) {
				$this->usunPlikiZdjecia($config->phFileOld);
				$q = "UPDATE ".BLOWPISY." SET phFile = '".tools::__mres($config->pgID,false,true)."_".tools::__link($file['name'])."' WHERE phID = ".tools::__mres($config->phID);
				tools::__adodb('exec',$q,true,$this->db);
				$up=move_uploaded_file($file['tmp_name'],  "{$this->BlogRootPath}".tools::__mres($config->pgID,false,true)."_".tools::__link($file['name']) );
			}else{
				$up = false;
			}
		}

	}
	
	protected function zablokujOdblokujZdjecie($blwID_){
		$phStatus = tools::__adodb('getOne',"SELECT phStatus FROM ".BLOWPISY." WHERE phID = '{$blwID_}'",true,$this->db);
		$phStatus = ($phStatus) ? 0 : 1;
		$q__ = "UPDATE ".BLOWPISY." SET phStatus = '{$phStatus}' WHERE phID = ".tools::__mres($blwID_);
		tools::__adodb('exec',$q__,true,$this->db);
	}

	protected function zablokujOdblokujGalerie($blcID_){
		$pgStatus = tools::__adodb('getOne',"SELECT pgStatus FROM ".BLCATEGO." WHERE pgID = '{$blcID_}'",true,$this->db);
		$pgStatus = ($pgStatus) ? 0 : 1;
		$q__ = "UPDATE ".BLCATEGO." SET pgStatus = '{$pgStatus}' WHERE pgID = ".tools::__mres($blcID_);
		tools::__adodb('exec',$q__,true,$this->db);
	}
	
	protected function zapiszDaneWpisuBloga($blwID = null){
		global $config;
		
		if(is_array($config->blwTemat)){
			foreach ($config->blwTemat as $lang => $blwTemat) {
				$q__ = "SELECT COUNT(*) FROM ".BLOWPISY." a 
					LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
					WHERE b.blwLang = '{$lang}' AND a.blwID = '{$blwID}'";
				$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
				if($istnieje == 1){
					$q__ = "UPDATE ".BLOWPILA." SET blwTemat = ".tools::__mres($blwTemat)." 
						WHERE blwID = ".tools::__mres($blwID)." AND blwLang = ".tools::__mres($lang);
					tools::__adodb('exec',$q__,true,$this->db);	
				}else{
					$q__ = "INSERT INTO ".BLOWPILA." (blwID,blwLang,blwTemat) 
					VALUES (".tools::__mres($blwID).",'{$lang}',".tools::__mres($blwTemat).")";
					tools::__adodb('exec',$q__,true,$this->db);		
				}
			}
			
		}else{
			$q__ = "UPDATE ".BLOWPILA." SET blwTemat = ".tools::__mres($config->blwTemat)."				 
				WHERE blwID = ".tools::__mres($blwID)." AND blwLang = ".tools::__mres($config->blwLang);
			tools::__adodb('exec',$q__,true,$this->db);
		}	

		if(is_array($config->blwWpis)){
				foreach ($config->blwWpis as $lang => $Opis__) {
					$q__ = "SELECT COUNT(*) FROM ".BLOWPISY." a 
						LEFT JOIN ".BLOWPILA." b ON b.blwID = a.blwID 
						WHERE b.blwLang = '{$lang}' AND a.blwID = '{$blwID}'";
					$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
					if($istnieje == 1){
						$q__ = "UPDATE ".BLOWPILA." SET blwWpis = ".tools::__mres($Opis__)."
							WHERE blwID = ".tools::__mres($blwID)." AND blwLang = ".tools::__mres($lang);
						tools::__adodb('exec',$q__,true,$this->db);	
					}else{
						$q__ = "INSERT INTO ".BLOWPILA." (blwID,blwLang,blwWpis) 
						VALUES (".tools::__mres($blwID).",'{$lang}',".tools::__mres($Opis__).")";
						tools::__adodb('exec',$q__,true,$this->db);		
					}
				}
			}
	}
	
	protected function usunZdjeciePG($blwID_){
		tools::__adodb("exec","DELETE FROM ".BLOWPILA." WHERE blwID = '{$blwID_}'",true,$this->db);
		$is_deleted = tools::__adodb("exec","DELETE FROM ".BLOWPISY." WHERE blwID = '{$blwID_}'",true,$this->db);
		if ($is_deleted){			
			//$this->usunPlikiZdjecia($file_);
		}
	}
	
	
	protected function usunPlikiZdjecia($file_){
			$__thumbs = $this->pobierzListePlkowGalerii($this->BlogRootPath);
	
			foreach ($__thumbs as $__thumb){
				$__is_del = $this->usunPlikiZDysku($__thumb);
			}
			
			$__is_del = $this->usunPlikiZDysku("{$this->BlogRootPath}{$file_}");
	}
	
	protected function usunKategorieBloga($blcID_){
		$phFiles_ = tools::__adodb("getAll","SELECT blwID FROM ".BLOWPISY." a WHERE a.blcID = '{$blcID_}'",true,$this->db);
		tools::__adodb("exec","DELETE FROM ".BLCATEGO." WHERE blcID = '{$blcID_}'",true,$this->db);
		tools::__adodb("exec","DELETE FROM ".BLCATELA." WHERE blcID = '{$blcID_}'",true,$this->db);
		foreach ($phFiles_ as $key => $file_) {			
			tools::__adodb("exec","DELETE FROM ".BLOWPILA." WHERE blwID = '{$file_['blwID']}'",true,$this->db);
			$is_deleted = tools::__adodb("exec","DELETE FROM ".BLOWPISY." WHERE blwID = '{$file_['blwID']}'",true,$this->db);
			if ($is_deleted){				
			 	//$__thumbs = $this->pobierzListePlkowGalerii($this->BlogRootPath);
		
				foreach ($__thumbs as $__thumb){
					//$__is_del = $this->usunPlikiZDysku($__thumb);
				}			
				//$__is_del = $this->usunPlikiZDysku("{$this->BlogRootPath}{$file_['phFile']}");
			}
		}
	}
	
	protected function pobierzListePlkowGalerii($target){
		global $files,$file_;
		$exceptions=array('.','..');
		$pattern="({$file_['phFile']}(.*).thumb$)";
		if (!$sourcedir=@opendir($target)) return false;
		$i=0;
		while(false!==($sibling=readdir($sourcedir))){
			if(!in_array($sibling,$exceptions)){
				$object=str_replace('//','/',$target.'/'.$sibling);
				if(is_dir($object)){
					$this->pobierzListePlkowGalerii($object);
				}
				
				if(is_file($object) && preg_match($pattern,$object)){
					$files[$i] = $object;
				}
				$i++;
			}
		}
		closedir($sourcedir);
		return $files;	
	}
	
	protected function usunPlikiZDysku($__file){
		try {
			$ret = array();
			if(file_exists($__file)){
				$result = @unlink($__file);
				$ret[0] = (!$result) ? false : true;
				$ret[1] = (!$result) ? "$__file został usunięty." : 'Error: file '.$__file. ' not deleted.';
			}else{
				$ret[0] = false;
				$ret[1] = 'Error: file '.$__file. ' not exists.';
			}
			return $ret;
		}catch ( Exception  $e ){
			$ret[0] = false;
			$ret[1] = $e->getMessage();	
			return $ret;		
		}
	}
}